package com.swpu.project.service.impl;


import com.swpu.project.common.BaseResponse;
import com.swpu.project.constant.RedisConstant;
import com.swpu.project.model.entity.LoginUser;
import com.swpu.project.model.entity.User;
import com.swpu.project.service.LoginService;
import com.swpu.project.util.JwtUtil;
import com.swpu.project.util.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    AuthenticationManager authenticationManager;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    RedisCache redisCache;
    @Override
    public BaseResponse login(User user) {
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());

        Authentication authenticate = authenticationManager.authenticate(usernamePasswordAuthenticationToken);

        if (authenticate == null) {
            throw new RuntimeException("登陆失败");
        }
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        User user1 = loginUser.getUser();
        String id = user1.getId().toString();
        String jwt = JwtUtil.createJWT(id);

        String key= RedisConstant.USER_TOKEN_PREFIX +id;
         redisCache.setCacheObject(key,loginUser);
        HashMap<String, String> stringStringHashMap = new HashMap<>();
        stringStringHashMap.put("token",jwt);

        return new BaseResponse(200,"登录成功",stringStringHashMap);
    }

    @Override
    public BaseResponse logout() {
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser principal = (LoginUser)authentication.getPrincipal();
        Long id = principal.getUser().getId();
        String key=RedisConstant.USER_TOKEN_PREFIX+id;
        redisCache.deleteObject(key);
        return new BaseResponse(200,"登出成功",null);
    }


    public static void main(String[] args) {

        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode("1234");
        String encode2 = bCryptPasswordEncoder.encode("1234");
        System.out.println(encode);
        boolean matches = bCryptPasswordEncoder.matches("1234", encode);
        System.out.println(matches);

    }

}
